package com.github.niefy.modules.sys.controller;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.niefy.common.utils.PageUtils;
import com.github.niefy.common.utils.R;
import com.github.niefy.modules.sys.entity.SysAddressEntity;
import com.github.niefy.modules.sys.service.SysAddressService;
import com.github.niefy.modules.wx.entity.WxQrCode;
import com.github.niefy.modules.wx.entity.WxUser;
import com.github.niefy.modules.wx.service.WxUserService;
import com.github.niefy.modules.wx.service.WxUserTagsService;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


/**
 * 地址表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2022-11-16 16:31:52
 */
@RestController
@RequestMapping("sys/address")
public class SysAddressController {
    @Autowired
    private SysAddressService sysAddressService;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    WxUserTagsService wxUserTagsService;

    @Autowired
    private WxUserService wxUserService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:address:list")
    public R list(@CookieValue String appid, @RequestParam Map<String, Object> params) {
        params.put("appid", appid);
        List<SysAddressEntity> list = sysAddressService.queryPage(params);

        return R.ok().put("page", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:address:info")
    public R info(@PathVariable("id") Long id) {
        SysAddressEntity sysAddress = sysAddressService.getById(id);

        return R.ok().put("address", sysAddress);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:address:save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@CookieValue String appid, @RequestBody SysAddressEntity sysAddress) {
        try {
            wxMpService.switchoverTo(appid);
            sysAddress.setAppid(appid);
            if (sysAddress.getType() == 0) {
                sysAddress.setParentId(0L);
                sysAddress.setParentName("");
            }

            //添加公众号标签
            sysAddress = sysAddressService.creatTag(appid, sysAddress);

            sysAddressService.save(sysAddress);
            if (sysAddress.getType() == 2) {
                //生成二维码
                sysAddress = sysAddressService.createQrCode(sysAddress);
                sysAddressService.updateById(sysAddress);
            }
        } catch (WxErrorException e) {
            WxError error = e.getError();
            if (45158 == error.getErrorCode()) {
                return R.error("标签名超长,添加失败！");
            } else if (45157 == error.getErrorCode()) {
                return R.error("标签名重复,添加失败！");
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:address:update")
    public R update(@CookieValue String appid, @RequestBody SysAddressEntity sysAddress) {
        try {
            wxMpService.switchoverTo(appid);

            List<WxUser> wxUsers = wxUserService.getUserList();
            if (0 != sysAddressService.list(new QueryWrapper<SysAddressEntity>().eq(true, "parent_id", sysAddress.getId())).size()) {
                return R.error("该地址存在下级，不能修改！");
            }
            for (WxUser wxUser : wxUsers) {
                for (Object selectTagid : wxUser.getTagidList()) {
                    if (Long.valueOf(String.valueOf(selectTagid)).longValue() == sysAddress.getTagId()) {
                        return R.error("该地址被引用，不能修改！");
                    }
                }
            }

            if (sysAddress.getType() == 2) {
                sysAddress = sysAddressService.createQrCode(sysAddress);
            }
            sysAddress = sysAddressService.updateTag(appid, sysAddress);

            sysAddressService.updateById(sysAddress);

        } catch (WxErrorException e) {
            WxError error = e.getError();
            if (45158 == error.getErrorCode()) {
                return R.error("标签名超长,添加失败！");
            } else if (45157 == error.getErrorCode()) {
                return R.error("标签名重复,添加失败！");
            }
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:address:delete")
    public R delete(@CookieValue String appid, @RequestBody Long[] ids) {
        try {

            switch (sysAddressService.deleteTag(appid, ids)) {
                case 0:
                    sysAddressService.removeByIds(Arrays.asList(ids));
                    return R.ok();
                case 1:
                    return R.error("该地址存在下级，不能删除！");
                case 2:
                    return R.error("该地址被引用，不能删除！");
                default:

                    break;
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}
